<template>
  <div class="application-container">
    <div class="page-content">
      <!-- 搜索表单 -->
      <div class="form-container">
        <el-form :inline="true" class="search-form">
          <el-form-item label="申报状态" class="el-form-item">
            <el-select v-model="searchForm.status_id" placeholder="请选择申报状态">
              <el-option label="全部" value="" />
              <el-option label="审核中" value="1" />
              <el-option label="已拒绝" value="2" />
              <el-option label="已通过" value="3" />
              <el-option label="已结束" value="4" />
            </el-select>
          </el-form-item>
          <el-form-item label="授权名称" class="el-form-item">
            <el-input v-model="searchForm.username" placeholder="请输入授权名称" />
          </el-form-item>
          <el-form-item label="承办单位" class="el-form-item">
            <el-input v-model="searchForm.organizer" placeholder="请输入承办单位" />
          </el-form-item>
          <el-form-item label="考生人数" class="el-form-item">
            <el-input v-model="searchForm.numPeople" placeholder="请输入考生人数" />
          </el-form-item>
          <el-form-item label="开始时间" class="el-form-item">
            <el-date-picker
              v-model="searchForm.startTime"
              type="date"
              placeholder="请选择开始时间"
              value-format="YYYY-MM-DD"
              :disabled-date="
                (time) => {
                  if (searchForm.endTime) {
                    return time.getTime() > new Date(searchForm.endTime).getTime();
                  }
                  return false;
                }
              " />
          </el-form-item>
          <el-form-item label="结束时间" class="el-form-item">
            <el-date-picker
              v-model="searchForm.endTime"
              type="date"
              placeholder="请选择结束时间"
              value-format="YYYY-MM-DD"
              :disabled-date="
                (time) => {
                  if (searchForm.startTime) {
                    return time.getTime() < new Date(searchForm.startTime).getTime();
                  }
                  return false;
                }
              " />
          </el-form-item>
          <!-- <el-form-item label="授权名称" class="el-form-item">
              <el-select v-model="searchForm.user_id" placeholder="请选择授权名称">
                <el-option v-for="item in users" :key="item.id" :label="item.username" :value="item.id" />
              </el-select>
            </el-form-item> organizer numPeople-->
          <el-form-item>
            <el-button type="primary" @click="handleSearch" class="Button">查询</el-button>
            <el-button @click="resetForm" class="Button">重置</el-button>
          </el-form-item>
          <el-form-item v-if="mainStore.userInfo?.roleId !== 3">
            <el-button type="primary" @click="handleAdd" class="Button">
              <el-icon><Plus /></el-icon>添加申报
            </el-button>
            <el-button type="success" @click="handleExport" class="Button">
              <el-icon><Download /></el-icon>申报导出
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 添加申报对话框 -->
      <el-dialog v-model="dialogVisible" title="添加考试申报" width="60%" :before-close="handleClose">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="application-form">
          <!-- <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="授权名称" prop="title">
                <el-input v-model="form.title" placeholder="请输入授权名称" />
              </el-form-item>
            </el-col>
          </el-row> -->

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="授权名称" prop="name">
                <el-select v-model="form.name" placeholder="请选择授权名称">
                  <el-option v-for="item in users" :key="item.id" :label="item.username" :value="item.username" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="考级机构" prop="institution">
                <el-select v-model="form.institution" placeholder="请选择考级机构">
                  <el-option v-for="item in institutions" :key="item.id" :label="item.name" :value="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="承办单位" prop="organizer">
                <el-input v-model="form.organizer" placeholder="请输入承办单位" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="考级机构电话" prop="institution_phone">
                <el-input v-model="form.institution_phone" placeholder="请输入考级机构电话" disabled />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="承办单位电话" prop="organizer_phone">
                <el-input v-model="form.organizer_phone" placeholder="请输入承办单位电话" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="考级方式" prop="grading_method">
                <el-select v-model="form.grading_method" placeholder="请选择考级方式">
                  <el-option label="线下" value="线下" />
                  <el-option label="线上" value="线上" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开始时间" prop="startTime">
                <el-date-picker
                  v-model="form.startTime"
                  type="datetime"
                  placeholder="请选择开始时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :disabled-date="
                    (time) => {
                      if (form.endTime) {
                        return time.getTime() < Date.now() - 8.64e7 || time.getTime() > new Date(form.endTime).getTime();
                      }
                      return time.getTime() < Date.now() - 8.64e7;
                    }
                  " />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="打分形式" prop="scoring_method">
                <el-select v-model="form.scoring_method" placeholder="请选择打分形式">
                  <el-option label="线下" value="线下" />
                  <el-option label="线上" value="线上" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="结束时间" prop="endTime">
                <el-date-picker v-model="form.endTime" type="datetime" placeholder="请选择结束时间" value-format="YYYY-MM-DD HH:mm:ss" :disabled-date="disabledEndDate" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="承办活动" prop="undertake">
                <el-select v-model="form.undertake" placeholder="请选择承办活动">
                  <el-option v-for="item in activities" :key="item.id" :label="item.name" :value="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="考生人数" prop="numPeople">
                <el-input v-model.number="form.numPeople" placeholder="请输入考生人数" type="number" :min="1" :precision="0" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="报考专业" prop="applyMajor">
                <el-select v-model="form.applyMajor" placeholder="请选择报考专业">
                  <el-option v-for="item in specialties" :key="item.id" :label="item.name" :value="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="最低等级" prop="lowest_grade">
                <el-input v-model.number="form.lowest_grade" placeholder="请输入最低等级" type="number" :min="1" :precision="0" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最高等级" prop="top_grade">
                <el-input v-model.number="form.top_grade" placeholder="请输入最高等级" type="number" :min="1" :precision="0" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="考场数量" prop="examRooms">
                <el-input v-model.number="form.examRooms" placeholder="请输入考场数量" type="number" :min="1" :precision="0" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="考官人数" prop="examiner_num">
                <el-input v-model.number="form.examiner_num" placeholder="请输入考官人数" type="number" :min="1" :precision="0" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="考点负责人" prop="charge">
                <el-input v-model="form.charge" placeholder="请输入考点负责人" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="考点负责人电话" prop="charge_phone">
                <el-input v-model="form.charge_phone" maxlength="11" placeholder="请输入考点负责人电话" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="安全负责人" prop="secure">
                <el-input v-model="form.secure" placeholder="请输入安全负责人" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="安全负责人电话" prop="secure_phone">
                <el-input v-model="form.secure_phone" maxlength="11" placeholder="请输入安全负责人电话" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="省市区" prop="provincial">
                <el-cascader
                  v-model="form.provincial"
                  :options="areaOptions"
                  placeholder="请选择省市区"
                  :props="{
                    value: 'label',
                    label: 'label',
                    children: 'children',
                  }" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="详细地址" prop="address">
                <el-input v-model="form.address" placeholder="请输入详细地址" />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="备案回执" prop="tofile_img">
                <el-upload class="avatar-uploader" action="#" :auto-upload="false" :show-file-list="false" :on-change="handleReceiptChange" accept="image/*">
                  <img v-if="form.tofile_img" :src="imgUrls(form.tofile_img)" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                  <template #tip>
                    <div class="el-upload__tip">只能上传jpg/png文件</div>
                  </template>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="安全责任书" prop="safety_img">
                <el-upload class="avatar-uploader" action="#" :auto-upload="false" :show-file-list="false" :on-change="handleSafetyLetterChange" accept="image/*">
                  <img v-if="form.safety_img" :src="imgUrls(form.safety_img)" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                  <template #tip>
                    <div class="el-upload__tip">只能上传jpg/png文件</div>
                  </template>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row> -->
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm" :loading="submitting">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 查看弹框 -->
      <el-dialog v-model="viewDialogVisible" title="查看考试申报" width="60%">
        <div v-if="currentItem" class="view-content">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="授权名称">{{ currentItem.name }}</el-descriptions-item>
            <el-descriptions-item label="考级机构">{{ currentItem.institution }}</el-descriptions-item>
            <el-descriptions-item label="机构电话">{{ currentItem.institution_phone }}</el-descriptions-item>
            <el-descriptions-item label="承办单位">{{ currentItem.organizer }}</el-descriptions-item>
            <el-descriptions-item label="承办单位电话">{{ currentItem.organizer_phone }}</el-descriptions-item>
            <el-descriptions-item label="考级方式">{{ currentItem.grading_method }}</el-descriptions-item>
            <el-descriptions-item label="打分形式">{{ currentItem.scoring_method }}</el-descriptions-item>
            <el-descriptions-item label="开始时间">{{ formatDateTime(currentItem.startTime) }}</el-descriptions-item>
            <el-descriptions-item label="结束时间">{{ formatDateTime(currentItem.endTime) }}</el-descriptions-item>
            <el-descriptions-item label="承办活动">{{ currentItem.undertake }}</el-descriptions-item>
            <el-descriptions-item label="报考专业">{{ currentItem.applyMajor }}</el-descriptions-item>
            <el-descriptions-item label="考生人数">{{ currentItem.numPeople }}</el-descriptions-item>
            <el-descriptions-item label="最低等级">{{ currentItem.lowest_grade }}</el-descriptions-item>
            <el-descriptions-item label="最高等级">{{ currentItem.top_grade }}</el-descriptions-item>
            <el-descriptions-item label="考场数量">{{ currentItem.examRooms }}</el-descriptions-item>
            <el-descriptions-item label="考官人数">{{ currentItem.examiner_num }}</el-descriptions-item>
            <el-descriptions-item label="考点负责人">{{ currentItem.charge }}</el-descriptions-item>
            <el-descriptions-item label="考点负责人电话">{{ currentItem.charge_phone }}</el-descriptions-item>
            <el-descriptions-item label="安全负责人">{{ currentItem.secure }}</el-descriptions-item>
            <el-descriptions-item label="安全负责人电话">{{ currentItem.secure_phone }}</el-descriptions-item>
            <el-descriptions-item label="省市区">{{ currentItem.provincial.join('') }}</el-descriptions-item>
            <el-descriptions-item label="详细地址">{{ currentItem.address }}</el-descriptions-item>
            <!-- <el-descriptions-item label="备案回执">
              <img v-if="currentItem.tofile_img" :src="imgUrls(currentItem.tofile_img)" class="preview-img" @click="handlePreviewImage(currentItem.tofile_img)" />
              <span v-else>暂无图片</span>
            </el-descriptions-item>
            <el-descriptions-item label="安全责任书">
              <img v-if="currentItem.safety_img" :src="imgUrls(currentItem.safety_img)" class="preview-img" @click="handlePreviewImage(currentItem.safety_img)" />
              <span v-else>暂无图片</span>
            </el-descriptions-item> -->
          </el-descriptions>
        </div>
      </el-dialog>

      <!-- 添加网盘对话框 -->
      <el-dialog v-model="webdiskDialogVisible" :title="webdiskForm.status_id === 4 ? '查看网盘地址' : '编辑网盘地址'" width="30%">
        <el-form :model="webdiskForm">
          <el-form-item label="网盘地址" style="display: block">
            <template #label>
              <div>网盘地址</div>
            </template>
            <el-input v-model="webdiskForm.webdisk" type="textarea" :rows="4" autocomplete="off" style="width: 100%; margin-right: 20px" :readonly="webdiskForm.status_id === 4"></el-input>
          </el-form-item>
        </el-form>
        <template #footer v-if="webdiskForm.status_id !== 4">
          <span class="dialog-footer">
            <el-button @click="webdiskDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitWebdisk">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 审核对话框 -->
      <el-dialog v-model="auditDialogVisible" title="审核考试申报" width="30%">
        <div class="dialogBox">
          <div class="labelName">ID</div>
          <div class="labelValue">{{ currentItem.id }}</div>
        </div>
        <div class="dialogBox">
          <div class="labelName">授权名称</div>
          <div class="labelValue">{{ currentItem.name }}</div>
        </div>
        <div class="dialogBox">
          <div class="labelName">省市区</div>
          <div class="labelValue">{{ currentItem.provincial.join('') }}</div>
        </div>
        <div class="dialogBox">
          <div class="labelName">详细地址</div>
          <div class="labelValue">{{ currentItem.address }}</div>
        </div>
        <div class="dialogBox">
          <div class="labelName">考生人数</div>
          <div class="labelValue">{{ currentItem.numPeople }}</div>
        </div>
        <div class="dialogBox">
          <div class="labelName">当前状态</div>
          <div class="labelValue">{{ currentItem.ExamApplicationStatus.name }}</div>
        </div>
        <el-form :model="auditForm">
          <el-form-item label="审核状态">
            <el-select v-model="auditForm.status_id" placeholder="请选择审核状态">
              <el-option label="拒绝" :value="2"></el-option>
              <el-option label="通过" :value="3"></el-option>
              <el-option label="结束" :value="4"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="auditDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitAudit">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 编辑对话框 -->
      <el-dialog v-model="editDialogVisible" title="编辑考试申报" width="60%" :before-close="handleClose">
        <el-form ref="editFormRef" :model="editForm" :rules="editRules" label-width="120px" class="application-form">
          <!-- <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="授权名称" prop="title">
                <el-input v-model="editForm.title" placeholder="请输入授权名称" />
              </el-form-item>
            </el-col>
          </el-row> -->

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="授权名称" prop="name">
                <el-select v-model="editForm.name" placeholder="请选择授权名称">
                  <el-option v-for="item in users" :key="item.id" :label="item.username" :value="item.username" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="考级机构" prop="institution">
                <el-select v-model="editForm.institution" placeholder="请选择考级机构">
                  <el-option v-for="item in institutions" :key="item.id" :label="item.name" :value="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="机构电话" prop="institution_phone">
                <el-input v-model="editForm.institution_phone" placeholder="请输入机构电话" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="承办单位" prop="organizer">
                <el-input v-model="editForm.organizer" placeholder="请输入承办单位" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="承办单位电话" prop="organizer_phone">
                <el-input v-model="editForm.organizer_phone" placeholder="请输入承办单位电话" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="考级方式" prop="grading_method">
                <el-select v-model="editForm.grading_method" placeholder="请选择考级方式">
                  <el-option label="线下" value="线下" />
                  <el-option label="线上" value="线上" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="打分形式" prop="scoring_method">
                <el-select v-model="editForm.scoring_method" placeholder="请选择打分形式">
                  <el-option label="线下" value="线下" />
                  <el-option label="线上" value="线上" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开始时间" prop="startTime">
                <el-date-picker
                  v-model="editForm.startTime"
                  type="datetime"
                  placeholder="请选择开始时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :default-time="defaultTime"
                  :disabled-date="
                    (time) => {
                      if (editForm.endTime) {
                        return time.getTime() < Date.now() - 8.64e7 || time.getTime() > new Date(editForm.endTime).getTime();
                      }
                      return time.getTime() < Date.now() - 8.64e7;
                    }
                  " />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="结束时间" prop="endTime">
                <el-date-picker 
                  v-model="editForm.endTime" 
                  type="datetime" 
                  placeholder="请选择结束时间" 
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :default-time="defaultTime"
                  :disabled-date="disabledEditEndDate" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="承办活动" prop="undertake">
                <el-select v-model="editForm.undertake" placeholder="请选择承办活动">
                  <el-option v-for="item in activities" :key="item.id" :label="item.name" :value="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="报考专业" prop="applyMajor">
                <el-select v-model="editForm.applyMajor" placeholder="请选择报考专业">
                  <el-option v-for="item in specialties" :key="item.id" :label="item.name" :value="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="考生人数" prop="numPeople">
                <el-input v-model.number="editForm.numPeople" placeholder="请输入考生人数" type="number" :min="1" :precision="0" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="最低等级" prop="lowest_grade">
                <el-input v-model.number="editForm.lowest_grade" placeholder="请输入最低等级" type="number" :min="1" :precision="0" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最高等级" prop="top_grade">
                <el-input v-model.number="editForm.top_grade" placeholder="请输入最高等级" type="number" :min="1" :precision="0" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="考场数量" prop="examRooms">
                <el-input v-model.number="editForm.examRooms" placeholder="请输入考场数量" type="number" :min="1" :precision="0" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="考官人数" prop="examiner_num">
                <el-input v-model.number="editForm.examiner_num" placeholder="请输入考官人数" type="number" :min="1" :precision="0" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="考点负责人" prop="charge">
                <el-input v-model="editForm.charge" placeholder="请输入考点负责人" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="考点负责人电话" prop="charge_phone">
                <el-input v-model="editForm.charge_phone" placeholder="请输入考点负责人电话" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="安全负责人" prop="secure">
                <el-input v-model="editForm.secure" placeholder="请输入安全负责人" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="安全负责人电话" prop="secure_phone">
                <el-input v-model="editForm.secure_phone" placeholder="请输入安全负责人电话" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="省市区" prop="provincial">
                <el-cascader
                  v-model="editForm.provincial"
                  :options="areaOptions"
                  placeholder="请选择省市区"
                  :props="{
                    value: 'label', // 使用 label 作为 value 来匹配 ['重庆市', '重庆市', '渝中区']
                    label: 'label',
                    children: 'children',
                  }" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="详细地址" prop="address">
                <el-input v-model="editForm.address" placeholder="请输入详细地址" />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="备案回执" prop="tofile_img">
                <el-upload class="avatar-uploader" action="#" :auto-upload="false" :show-file-list="false" :on-change="handleReceiptChange" accept="image/*">
                  <img v-if="editForm.tofile_img" :src="imgUrls(editForm.tofile_img)" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                  <template #tip>
                    <div class="el-upload__tip">只能上传jpg/png文件</div>
                  </template>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="安全责任书" prop="safety_img">
                <el-upload class="avatar-uploader" action="#" :auto-upload="false" :show-file-list="false" :on-change="handleSafetyLetterChange" accept="image/*">
                  <img v-if="editForm.safety_img" :src="imgUrls(editForm.safety_img)" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                  <template #tip>
                    <div class="el-upload__tip">只能上传jpg/png文件</div>
                  </template>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row> -->
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitEdit">保存</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 表格 -->
      <el-table :data="tableData" border class="el-table">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="授权名称" width="260" />
        <el-table-column prop="applyMajor" label="报考专业" width="100" />
        <el-table-column prop="numPeople" label="考生人数" width="100" />
        <el-table-column label="开始时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column label="结束时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.ExamApplicationStatus?.name || getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="provincialTxt" label="省市区" width="170" />
        <el-table-column prop="address" label="详细地址" width="320" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <div class="button-group">
              <div class="button-row">
                <el-button type="primary" @click="handleView(scope.row)">查看</el-button>
                <el-button type="info" @click="downloadFileLinke(scope.row, 'filingTable')">备案表</el-button>
                <el-button type="primary" @click="downloadFileLinke(scope.row, 'brochureTable')">考试简章</el-button>
                <!-- <el-button type="info" @click="downloadFile(scope.row.filingTable)">备案表</el-button>
                <el-button type="primary" @click="downloadFile(scope.row.brochureTable)">考试简章</el-button> -->
              </div>
              <div class="button-row">
                <el-button type="success" @click="handleQRCode(scope.row)" :disabled="!canAccessRegistration(scope.row.status_id)">报名二维码</el-button>
                <el-button type="warning" @click="handleRegistrationLink(scope.row)" :disabled="!canAccessRegistration(scope.row.status_id)">报名链接</el-button>
                <el-button type="primary" @click="handleRegistrationForm(scope.row)" :disabled="!canDownloadRegistrationForm(scope.row.status_id)">报名表</el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="管理" width="160" fixed="right">
          <template #default="scope">
            <div class="button-group">
              <div class="button-row">
                <el-button type="success" @click="handleDisk(scope.row)">网盘</el-button>
                <el-button type="warning" @click="handleAudit(scope.row)" v-if="userRole >= 90" :disabled="scope.row.status_id === 4">审核</el-button>
              </div>
              <div class="button-row">
                <el-button type="primary" @click="handleEdit(scope.row)" v-if="userRole >= 80" :disabled="scope.row.status_id === 4">编辑</el-button>
                <el-button type="danger" @click="handleDelete(scope.row)" v-if="userRole >= 90">删除</el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无数据" />
        </template>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100, 200]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted, watch, computed } from 'vue';

  import { ElMessage, ElMessageBox } from 'element-plus';
  import { Plus, Download } from '@element-plus/icons-vue';
  import Http from '@/utils/http';

  import OSS from 'ali-oss';
  import { imgUrls, downloadFile, openFile } from '@/utils/utils';
  import { useMainStore } from '@/stores/useMain';
  import { regionData } from 'element-china-area-data';
  const areaOptions = ref(regionData);

  const Provincial = ref(['重庆市', '市辖区', '渝中区']);
  const mainStore = useMainStore();
  const userRole = computed(() => mainStore.userInfo?.role?.roleType || 0);

  const client = new OSS({
    region: 'oss-cn-chengdu',
    accessKeyId: 'LTAI5t8ySspV3RByRTKBdHdF',
    accessKeySecret: 'SalGEBIs14QFqZ7dmKnHvFquxtGBAh',
    bucket: 'yipei001',
    secure: true, // 使用 HTTPS
    endpoint: 'oss-cn-chengdu.aliyuncs.com', // 指定 endpoint
  });

  // 修改 OSS 客户端配置
  // const client = new OSS({
  //   region: 'oss-cn-chengdu',
  //   accessKeyId: 'LTAI5t6pEr2wMKtDAfWSwo1H',
  //   accessKeySecret: 'Nrn34ANQF6Dqi5Koo23jd2ljJadWq1',
  //   bucket: 'yipei',
  //   secure: true, // 使用 HTTPS
  //   endpoint: 'oss-cn-chengdu.aliyuncs.com', // 指定 endpoint
  // });
  // 搜索表单数据
  const searchForm = reactive({
    status_id: '',
    user_id: '', // 添加用户ID字段
    username: '', // 授权名称
    organizer: '', // 承办单位
    numPeople: '', // 考生人数
    startTime: '', // 开始时间
    endTime: '', // 结束时间
  });
  onMounted(() => {
    getExamOptions();
  });
  // 表格数据
  const tableData = ref([]);

  // 分页数据
  const currentPage = ref(1);
  const pageSize = ref(10);
  const total = ref(100);

  // 表单相关数据
  const dialogVisible = ref(false);
  const formRef = ref(null);
  const form = reactive({
    // title: '',
    name: '',
    user_id: '',
    institution: '',
    institution_id: '',
    institution_phone: '',
    organizer: '',
    organizer_phone: '',
    grading_method: '',
    scoring_method: '',
    startTime: '',
    endTime: '',
    undertake: '',
    activity_id: '',
    applyMajor: '',
    specialty_id: '',
    numPeople: '',
    lowest_grade: '',
    top_grade: '',
    examRooms: '',
    examiner_num: '',
    charge: '',
    charge_phone: '',
    secure: '',
    secure_phone: '',
    provincial: [],
    address: '',
    tofile_img: null,
    safety_img: null,
  });

  const users = ref([]);
  const institutions = ref([]);
  const specialties = ref([]);
  const activities = ref([]);

  const getExamOptions = async () => {
    const { code, data, msg } = await Http.get({
      url: '/yp_admin/getExamOptions',
      params: {
        user_id: searchForm.user_id || '',
      },
    });
    if (code != 200) return ElMessage.error(msg);
    users.value = data.users;
    institutions.value = data.institutions;
    specialties.value = data.specialties;
    activities.value = data.activities;

    // 如果只有一条用户数据，自动设置搜索表单的user_id
    if (users.value.length === 1) {
      searchForm.user_id = users.value[0].id;
      // 重新获取考试申报列表
    }
    getExamApplications();
  };

  const getExamApplications = async () => {
    try {
      const { code, data, msg } = await Http.post({
        url: '/yp_admin/getExamApplications',
        data: {
          page: currentPage.value,
          pageSize: pageSize.value,
          status_id: searchForm.status_id || '',
          user_id: searchForm.user_id || '',
          username: searchForm.username,
          organizer: searchForm.organizer,
          numPeople: searchForm.numPeople,
          startTime: searchForm.startTime,
          endTime: searchForm.endTime,
        },
      });

      if (code !== 200) return ElMessage.error(msg || '获取考试申报列表失败');
      data.items.forEach((item) => {
        item.provincialTxt = item.provincial;
        if (typeof item.provincial == 'string') {
          // 处理直辖市的情况
          if (['北京市', '上海市', '天津市', '重庆市'].some((city) => item.provincial.startsWith(city))) {
            const cityName = item.provincial.substring(0, 2) + '市';
            const parts = item.provincial.split(cityName);
            const remaining = parts[parts.length - 1];

            if (remaining.includes('市辖区')) {
              const district = remaining.replace('市辖区', '');
              const result = [cityName, '市辖区', district];
              item.provincial = result;
            } else if (remaining.includes('县')) {
              const county = remaining.replace(/^县/, '');
              const result = [cityName, '县', county];
              item.provincial = result;
            }
          } else {
            // 处理普通省份和自治区的情况
            const provincial = item.provincial;

            // 提取省级
            const provinceMatch = provincial.match(/(.+?(?:省|自治区))/);
            const province = provinceMatch ? provinceMatch[1] : '';
            let remaining = provincial.slice(province.length);

            // 提取市级
            const cityMatch = remaining.match(/(.+?(?:自治州|市))/);
            const city = cityMatch ? cityMatch[1] : '';
            remaining = remaining.slice(city.length);

            // 提取区县级
            const districtMatch = remaining.match(/(.+?(?:区|县|自治县|市))/);
            const district = districtMatch ? districtMatch[1] : '';

            item.provincial = [province, city, district].filter(Boolean);
          }
        }
      });
      tableData.value = data.items;
      total.value = data.total;
    } catch (error) {
      console.error('获取考试申报列表失败:', error);
      ElMessage.error('获取考试申报列表失败');
    }
  };

  // 监听users和institutions数组变化
  watch(
    users,
    (newVal) => {
      if (newVal.length === 1) {
        form.name = newVal[0].username;
        form.user_id = newVal[0].id;
      }
    },
    { immediate: true },
  );

  watch(
    institutions,
    (newVal) => {
      if (newVal.length === 1) {
        form.institution = newVal[0].name;
        form.institution_id = newVal[0].id;
        form.institution_phone = newVal[0].phone;
      }
    },
    { immediate: true },
  );

  // 监听考级机构选择变化
  watch(
    () => form.institution,
    (newVal) => {
      if (newVal) {
        const selectedInstitution = institutions.value.find((item) => item.name === newVal);
        if (selectedInstitution) {
          form.institution_phone = selectedInstitution.phone;
          form.institution_id = selectedInstitution.id;
        }
      }
    },
  );

  // 监听activities数组变化
  watch(
    activities,
    (newVal) => {
      if (newVal.length === 1) {
        form.undertake = newVal[0].name;
        form.activity_id = newVal[0].id;
      }
    },
    { immediate: true },
  );

  // 监听specialties数组变化
  watch(
    specialties,
    (newVal) => {
      if (newVal.length === 1) {
        form.applyMajor = newVal[0].name;
        form.specialty_id = newVal[0].id;
      }
    },
    { immediate: true },
  );

  // 添加监听器
  watch(
    () => form.undertake,
    (newVal) => {
      if (newVal) {
        const selectedActivity = activities.value.find((item) => item.name === newVal);
        if (selectedActivity) {
          form.activity_id = selectedActivity.id;
        }
      }
    },
  );

  watch(
    () => form.applyMajor,
    (newVal) => {
      if (newVal) {
        const selectedSpecialty = specialties.value.find((item) => item.name === newVal);
        if (selectedSpecialty) {
          form.specialty_id = selectedSpecialty.id;
        }
      }
    },
  );

  // 添加 name 的监听器
  watch(
    () => form.name,
    (newVal) => {
      if (newVal) {
        const selectedUser = users.value.find((item) => item.username === newVal);
        if (selectedUser) {
          form.user_id = selectedUser.id;
        }
      }
    },
  );

  // 表单验证规则
  const rules = {
    name: [{ required: true, message: '请选择授权名称', trigger: 'change' }],
    // title: [{ required: true, message: '请输入授权名称', trigger: 'blur' }],
    institution: [{ required: true, message: '请选择考级机构', trigger: 'change' }],
    institution_phone: [{ required: true, message: '请输入机构电话', trigger: 'blur' }],
    organizer: [{ required: true, message: '请输入承办单位', trigger: 'blur' }],
    organizer_phone: [{ required: true, message: '请输入承办单位电话', trigger: 'blur' }],
    grading_method: [{ required: true, message: '请选择考级方式', trigger: 'change' }],
    scoring_method: [{ required: true, message: '请选择打分形式', trigger: 'change' }],
    startTime: [
      { required: true, message: '请选择开始时间', trigger: 'change' },
      {
        validator: (rule, value, callback) => {
          if (form.endTime && new Date(value) > new Date(form.endTime)) {
            callback(new Error('开始时间不能大于结束时间'));
          } else {
            callback();
          }
        },
        trigger: 'change',
      },
    ],
    endTime: [
      { required: true, message: '请选择结束时间', trigger: 'change' },
      {
        validator: (rule, value, callback) => {
          if (form.startTime && new Date(value) < new Date(form.startTime)) {
            callback(new Error('结束时间不能小于开始时间'));
          } else {
            callback();
          }
        },
        trigger: 'change',
      },
    ],
    undertake: [{ required: true, message: '请选择承办活动', trigger: 'change' }],
    applyMajor: [{ required: true, message: '请选择报考专业', trigger: 'change' }],
    numPeople: [
      { required: true, message: '请输入考生人数', trigger: 'blur' },
      { type: 'number', message: '考生人数必须为数字', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value < 1) {
            callback(new Error('考生人数必须大于等于1'));
          } else if (!Number.isInteger(value)) {
            callback(new Error('考生人数必须为整数'));
          } else {
            callback();
          }
        },
        trigger: 'blur',
      },
    ],
    lowest_grade: [
      { required: true, message: '请输入最低等级', trigger: 'blur' },
      { type: 'number', message: '最低等级必须为数字', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value < 1) {
            callback(new Error('最低等级必须大于等于1'));
          } else if (value > 10) {
            callback(new Error('最低等级不能大于10'));
          } else if (form.top_grade && value >= form.top_grade) {
            callback(new Error('最低等级必须小于最高等级'));
          } else if (!Number.isInteger(value)) {
            callback(new Error('最低等级必须为整数'));
          } else {
            callback();
          }
        },
        trigger: 'blur',
      },
    ],
    top_grade: [
      { required: true, message: '请输入最高等级', trigger: 'blur' },
      { type: 'number', message: '最高等级必须为数字', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value < 1) {
            callback(new Error('最高等级必须大于等于1'));
          } else if (value > 10) {
            callback(new Error('最高等级不能大于10'));
          } else if (form.lowest_grade && value <= form.lowest_grade) {
            callback(new Error('最高等级必须大于最低等级'));
          } else if (!Number.isInteger(value)) {
            callback(new Error('最高等级必须为整数'));
          } else {
            callback();
          }
        },
        trigger: 'blur',
      },
    ],
    examRooms: [
      { required: true, message: '请输入考场数量', trigger: 'blur' },
      { type: 'number', message: '考场数量必须为数字', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value < 1) {
            callback(new Error('考场数量必须大于等于1'));
          } else if (!Number.isInteger(value)) {
            callback(new Error('考场数量必须为整数'));
          } else {
            callback();
          }
        },
        trigger: 'blur',
      },
    ],
    examiner_num: [
      { required: true, message: '请输入考官人数', trigger: 'blur' },
      { type: 'number', message: '考官人数必须为数字', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value < 1) {
            callback(new Error('考官人数必须大于等于1'));
          } else if (!Number.isInteger(value)) {
            callback(new Error('考官人数必须为整数'));
          } else {
            callback();
          }
        },
        trigger: 'blur',
      },
    ],
    charge: [
      { required: true, message: '请输入考点负责人', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value && value === form.secure) {
            callback(new Error('考点负责人与安全负责人不能相同'));
          } else {
            callback();
          }
        },
        trigger: 'blur',
      },
    ],
    charge_phone: [
      { required: true, message: '请输入考点负责人电话', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value && value === form.secure_phone) {
            callback(new Error('考点负责人电话与安全负责人电话不能相同'));
          } else {
            callback();
          }
        },
        trigger: 'blur',
      },
    ],
    secure: [
      { required: true, message: '请输入安全负责人', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value && value === form.charge) {
            callback(new Error('安全负责人与考点负责人不能相同'));
          } else {
            callback();
          }
        },
        trigger: 'blur',
      },
    ],
    secure_phone: [
      { required: true, message: '请输入安全负责人电话', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value && value === form.charge_phone) {
            callback(new Error('安全负责人电话与考点负责人电话不能相同'));
          } else {
            callback();
          }
        },
        trigger: 'blur',
      },
    ],
    provincial: [{ required: true, message: '请选择省市区', trigger: 'change' }],
    address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
    // tofile_img: [{ required: true, message: '请上传备案回执', trigger: 'change' }],
    // safety_img: [{ required: true, message: '请上传安全责任书', trigger: 'change' }],
  };

  // 编辑表单的验证规则
  const editRules = {
    name: [{ required: true, message: '请选择授权名称', trigger: 'change' }],
    // title: [{ required: true, message: '请输入授权名称', trigger: 'blur' }],
    institution: [{ required: true, message: '请选择授权名称', trigger: 'change' }],
    institution_phone: [{ required: true, message: '请输入机构电话', trigger: 'blur' }],
    organizer: [{ required: true, message: '请输入承办单位', trigger: 'blur' }],
    organizer_phone: [{ required: true, message: '请输入承办单位电话', trigger: 'blur' }],
    grading_method: [{ required: true, message: '请选择考级方式', trigger: 'change' }],
    scoring_method: [{ required: true, message: '请选择打分形式', trigger: 'change' }],
    startTime: [
      { required: true, message: '请选择开始时间', trigger: 'change' },
      {
        validator: (rule, value, callback) => {
          if (editForm.endTime && new Date(value) > new Date(editForm.endTime)) {
            callback(new Error('开始时间不能大于结束时间'));
          } else {
            callback();
          }
        },
        trigger: 'change',
      },
    ],
    endTime: [
      { required: true, message: '请选择结束时间', trigger: 'change' },
      {
        validator: (rule, value, callback) => {
          if (editForm.startTime && new Date(value) < new Date(editForm.startTime)) {
            callback(new Error('结束时间不能小于开始时间'));
          } else {
            callback();
          }
        },
        trigger: 'change',
      },
    ],
    undertake: [{ required: true, message: '请选择承办活动', trigger: 'change' }],
    applyMajor: [{ required: true, message: '请选择报考专业', trigger: 'change' }],
    numPeople: [
      { required: true, message: '请输入考生人数', trigger: 'blur' },
      { type: 'number', message: '考生人数必须为数字', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value < 1) {
            callback(new Error('考生人数必须大于等于1'));
          } else if (!Number.isInteger(value)) {
            callback(new Error('考生人数必须为整数'));
          } else {
            callback();
          }
        },
        trigger: 'blur',
      },
    ],
    lowest_grade: [
      { required: true, message: '请输入最低等级', trigger: 'blur' },
      { type: 'number', message: '最低等级必须为数字', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value < 1) {
            callback(new Error('最低等级必须大于等于1'));
          } else if (value > 10) {
            callback(new Error('最低等级不能大于10'));
          } else if (editForm.top_grade && value >= editForm.top_grade) {
            callback(new Error('最低等级必须小于最高等级'));
          } else if (!Number.isInteger(value)) {
            callback(new Error('最低等级必须为整数'));
          } else {
            callback();
          }
        },
        trigger: 'blur',
      },
    ],
    top_grade: [
      { required: true, message: '请输入最高等级', trigger: 'blur' },
      { type: 'number', message: '最高等级必须为数字', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value < 1) {
            callback(new Error('最高等级必须大于等于1'));
          } else if (value > 10) {
            callback(new Error('最高等级不能大于10'));
          } else if (editForm.lowest_grade && value <= editForm.lowest_grade) {
            callback(new Error('最高等级必须大于最低等级'));
          } else if (!Number.isInteger(value)) {
            callback(new Error('最高等级必须为整数'));
          } else {
            callback();
          }
        },
        trigger: 'blur',
      },
    ],
    examRooms: [
      { required: true, message: '请输入考场数量', trigger: 'blur' },
      { type: 'number', message: '考场数量必须为数字', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value < 1) {
            callback(new Error('考场数量必须大于等于1'));
          } else if (!Number.isInteger(value)) {
            callback(new Error('考场数量必须为整数'));
          } else {
            callback();
          }
        },
        trigger: 'blur',
      },
    ],
    examiner_num: [
      { required: true, message: '请输入考官人数', trigger: 'blur' },
      { type: 'number', message: '考官人数必须为数字', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value < 1) {
            callback(new Error('考官人数必须大于等于1'));
          } else if (!Number.isInteger(value)) {
            callback(new Error('考官人数必须为整数'));
          } else {
            callback();
          }
        },
        trigger: 'blur',
      },
    ],
    charge: [
      { required: true, message: '请输入考点负责人', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value && value === editForm.secure) {
            callback(new Error('考点负责人与安全负责人不能相同'));
          } else {
            callback();
          }
        },
        trigger: 'blur',
      },
    ],
    charge_phone: [
      { required: true, message: '请输入考点负责人电话', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value && value === editForm.secure_phone) {
            callback(new Error('考点负责人电话与安全负责人电话不能相同'));
          } else {
            callback();
          }
        },
        trigger: 'blur',
      },
    ],
    secure: [
      { required: true, message: '请输入安全负责人', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value && value === editForm.charge) {
            callback(new Error('安全负责人与考点负责人不能相同'));
          } else {
            callback();
          }
        },
        trigger: 'blur',
      },
    ],
    secure_phone: [
      { required: true, message: '请输入安全负责人电话', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value && value === editForm.charge_phone) {
            callback(new Error('安全负责人电话与考点负责人电话不能相同'));
          } else {
            callback();
          }
        },
        trigger: 'blur',
      },
    ],
    provincial: [{ required: true, message: '请选择省市区', trigger: 'change' }],
    address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
    // tofile_img: [{ required: true, message: '请上传备案回执', trigger: 'change' }],
    // safety_img: [{ required: true, message: '请上传安全责任书', trigger: 'change' }],
  };

  // 状态映射
  const getStatusType = (status) => {
    const map = {
      pending: 'warning',
      approved: 'success',
      rejected: 'danger',
    };
    return map[status];
  };

  const getStatusText = (status) => {
    const map = {
      pending: '待审核',
      approved: '已通过',
      rejected: '已驳回',
    };
    return map[status];
  };

  // 方法
  const handleSearch = () => {
    currentPage.value = 1; // 重置页码到第一页
    getExamApplications();
  };

  const resetForm = () => {
    // 重置状态选择
    searchForm.status_id = '';
    searchForm.username = '';
    searchForm.organizer = '';
    searchForm.numPeople = '';
    searchForm.startTime = '';
    searchForm.endTime = '';
    // 如果只有一个用户，保持user_id不变，否则重置为空
    if (users.value.length === 1) {
      searchForm.user_id = users.value[0].id;
    } else {
      searchForm.user_id = '';
    }

    // 重置后重新获取列表数据
    currentPage.value = 1; // 重置页码到第一页
    getExamApplications();
  };

  // 添加查看弹框相关的数据
  const viewDialogVisible = ref(false);
  const currentItem = ref(null);

  // 修改查看方法
  const handleView = (row) => {
    currentItem.value = row;
    viewDialogVisible.value = true;
  };

  const handleApprove = (row) => {
    ElMessage.success('审核通过成功');
  };

  const handleReject = (row) => {
    ElMessage.warning('已驳回申请');
  };

  const handleSizeChange = (val) => {
    pageSize.value = val;
    getExamApplications();
  };

  const handleCurrentChange = (val) => {
    currentPage.value = val;
    getExamApplications();
  };

  // 修改文件上传处理方法
  const handleReceiptChange = async (file) => {
    try {
      const fileName = `images/${Date.now()}-${file.raw.name}`;
      const result = await client.put(fileName, file.raw);
      editForm.tofile_img = `/${fileName}`;
      form.tofile_img = `/${fileName}`;

      ElMessage.success('上传成功');
    } catch (error) {
      console.error('上传失败:', error);
      ElMessage.error('上传失败');
    }
  };

  const handleSafetyLetterChange = async (file) => {
    try {
      const fileName = `images/${Date.now()}-${file.raw.name}`;
      const result = await client.put(fileName, file.raw);
      editForm.safety_img = `/${fileName}`;
      form.safety_img = `/${fileName}`;
      ElMessage.success('上传成功');
    } catch (error) {
      console.error('上传失败:', error);
      ElMessage.error('上传失败');
    }
  };

  // 处理对话框关闭
  const handleClose = (done) => {
    ElMessageBox.confirm('确认关闭？')
      .then(() => {
        done();
      })
      .catch(() => {
        // 取消关闭
      });
  };

  // 添加一个变量控制提交状态
  const submitting = ref(false);

  // 提交表单
  const submitForm = async () => {
    // 如果正在提交或表单引用不存在,直接返回
    if (!formRef.value || submitting.value) return;

    try {
      // 表单验证
      await formRef.value.validate();

      // 设置提交状态为true
      submitting.value = true;

      // 处理省市区数据
      const formData = { ...form };
      if (Array.isArray(formData.provincial)) {
        formData.provincial = formData.provincial.join('');
      }
      if (formData.name) formData.title = formData.name;

      // 发送请求
      const { code, msg } = await Http.post({
        url: '/yp_admin/addExamApplication',
        data: formData,
      });

      if (code === 200) {
        ElMessage.success('提交成功');
        dialogVisible.value = false;
        getExamApplications();
      } else {
        ElMessage.error(msg || '提交失败');
      }
    } catch (error) {
      // 区分表单验证错误和其他错误
      if (error.message) {
        ElMessage.error(error.message);
      } else {
        ElMessage.error('提交失败');
      }
      console.error('提交失败:', error);
    } finally {
      // 无论成功失败都要重置提交状态
      submitting.value = false;
    }
  };
  // const submitForm = async () => {
  //   if (!formRef.value || submitting.value) return;
  //   await formRef.value.validate(async (valid, fields) => {
  //     if (valid) {
  //       try {
  //         submitting.value = true;
  //         // 处理省市区数据
  //         const formData = { ...form };
  //         if (Array.isArray(formData.provincial)) {
  //           formData.provincial = formData.provincial.join('');
  //         }
  //         if (formData.name) formData.title = formData.name;
  //         const { code, msg } = await Http.post({
  //           url: '/yp_admin/addExamApplication',
  //           data: formData,
  //         });
  //         if (code === 200) {
  //           ElMessage.success('提交成功');
  //           dialogVisible.value = false;
  //           getExamApplications();
  //         } else {
  //           ElMessage.error(msg || '提交失败');
  //         }
  //       } catch (error) {
  //         ElMessage.error('提交失败');
  //       } finally {
  //         submitting.value = false;
  //       }
  //     } else {
  //       console.log('表单验证失败:', fields);
  //     }
  //   });
  // };

  // 打开添加申报对话框
  const handleAdd = () => {
    dialogVisible.value = true;
  };

  // 禁用开始时间之前的日期
  const disabledStartDate = (time) => {
    return time.getTime() < Date.now() - 8.64e7; // 禁用今天之前的日期
  };

  // 禁用结束时间小于开始时间的日期
  const disabledEndDate = (time) => {
    if (!form.startTime) {
      return time.getTime() < Date.now() - 8.64e7;
    }
    // 仅比较日期部分，忽略时间部分
    const startDate = new Date(form.startTime);
    const timeDate = new Date(time);

    // 设置时间为00:00:00以只比较日期
    const startDateOnly = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate());
    const timeDateOnly = new Date(timeDate.getFullYear(), timeDate.getMonth(), timeDate.getDate());

    return timeDateOnly < startDateOnly;
  };

  // 为编辑表单添加结束时间禁用函数
  const disabledEditEndDate = (time) => {
    if (!editForm.startTime) {
      return time.getTime() < Date.now() - 8.64e7;
    }
    // 仅比较日期部分，忽略时间部分
    const startDate = new Date(editForm.startTime);
    const timeDate = new Date(time);

    // 设置时间为00:00:00以只比较日期
    const startDateOnly = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate());
    const timeDateOnly = new Date(timeDate.getFullYear(), timeDate.getMonth(), timeDate.getDate());

    return timeDateOnly < startDateOnly;
  };

  // 在 script setup 中添加日期格式化函数
  const formatDateTime = (dateStr) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  };

  // 添加对应的处理方法
  const handleDisk = (row) => {
    webdiskForm.id = row.id;
    webdiskForm.webdisk = row.webdisk || '';
    webdiskForm.status_id = row.status_id;
    webdiskDialogVisible.value = true;
  };

  const handleAudit = (row) => {
    currentItem.value = row;
    auditForm.id = row.id;
    auditForm.status_id = '';
    auditDialogVisible.value = true;
  };

  // 添加判断是否可以下载报名表的方法
  const canDownloadRegistrationForm = (status) => {
    return status === 3 || status === 4;
  };

  // 修改报名表处理方法
  const handleRegistrationForm = async (row) => {
    try {
      const { code, data, msg } = await Http.post({
        url: '/yp_admin/getExamApplicationData',
        data: {
          examApplicationId: row.id,
        },
      });

      if (code !== 200) {
        return ElMessage.error(msg || '获取报名表失败');
      }

      if (!data.url) {
        return ElMessage.warning('暂无报名表数据');
      }

      const downloadUrl = imgUrls(data.url);
      window.open(downloadUrl, '_blank');

      ElMessage.success('导出成功');
    } catch (error) {
      console.error('获取报名表失败:', error);
      ElMessage.error('获取报名表失败');
    }
  };

  // 修改报名链接处理方法
  const handleRegistrationLink = (row) => {
    if (!row.applylink) return ElMessage.warning('暂无报名链接');
    if (row.status_id == 4) return ElMessage.warning('活动已结束');
    // 创建临时输入框复制文本
    const input = document.createElement('input');
    input.value = row.applylink;
    document.body.appendChild(input);
    input.select();
    document.execCommand('copy');
    document.body.removeChild(input);
    ElMessage.success('链接已复制到剪贴板');
  };

  // 修改报名二维码处理方法
  const handleQRCode = (row) => {
    if (!row.qrcodeImg) return ElMessage.warning('暂无报名二维码');
    if (row.status_id == 4) return ElMessage.warning('活动已结束');
    window.open(imgUrls(row.qrcodeImg));
  };

  const editDialogVisible = ref(false);
  const editFormRef = ref(null);
  const editForm = ref({
    id: '',
    name: '',
    title: '',
    institution: '',
    institution_phone: '',
    organizer: '',
    organizer_phone: '',
    grading_method: '',
    scoring_method: '',
    startTime: '',
    endTime: '',
    undertake: '',
    activity_id: '',
    applyMajor: '',
    specialty_id: '',
    numPeople: '',
    lowest_grade: '',
    top_grade: '',
    examRooms: '',
    examiner_num: '',
    charge: '',
    charge_phone: '',
    secure: '',
    secure_phone: '',
    provincial: [],
    address: '',
    tofile_img: null,
    safety_img: null,
  });

  const defaultTime = ref(new Date(2000, 1, 1, 8, 0, 0));  // 添加默认时间变量

  const downloadFileLinke = async (row, fileType) => {
    // 定义文件类型映射
    const fileTypeMap = {
      filingTable: {
        field: 'filingTable',
        name: '备案表',
      },
      brochureTable: {
        field: 'brochureTable',
        name: '考试简章',
      },
    };
    const { field, name } = fileTypeMap[fileType];

    // 如果文件已存在,直接下载
    if (row[field]) {
      downloadFile(row[field]);
      return;
    }

    // 文件不存在,需要重新生成
    try {
      // 准备提交数据
      const formData = {
        ...row,
        lowest_grade: Number(row.lowest_grade),
        top_grade: Number(row.top_grade),
        provincial: Array.isArray(row.provincial) ? row.provincial.join('') : row.provincial,
      };

      // 发送请求
      const { code, data, msg } = await Http.post({
        url: '/yp_admin/editExamApplication',
        data: formData,
      });

      if (code === 200 && data?.[field]) {
        downloadFile(data[field]);
        getExamApplications(); // 刷新列表
      } else {
        ElMessage.error(`获取${name}失败: ${msg || '未知错误'}`);
      }
    } catch (error) {
      console.error(`获取${name}失败:`, error);
      ElMessage.error(`获取${name}失败: ${error.message || '未知错误'}`);
    }

    // if (!row.filingTable || !row.brochureTable) {
    //   try {
    //     // 准备提交数据
    //     const formData = {
    //       ...row,
    //       lowest_grade: Number(row.lowest_grade),
    //       top_grade: Number(row.top_grade),
    //       provincial: Array.isArray(row.provincial) ? row.provincial.join('') : row.provincial
    //     };

    //     // 直接发送请求
    //     const { code, data, msg } = await Http.post({
    //       url: '/yp_admin/editExamApplication',
    //       data: formData,
    //     });

    //     if (code === 200 && data?.filingTable) {
    //       if(type == 'filingTable'){
    //         downloadFile(data.filingTable);
    //       }else if(type == 'brochureTable'){
    //         downloadFile(data.brochureTable);
    //       }

    //       getExamApplications(); // 刷新列表
    //     } else {
    //       ElMessage.error(msg || '获取备案表失败');
    //     }
    //   } catch (error) {
    //     console.error('获取备案表失败:', error);
    //     ElMessage.error('获取备案表失败');
    //   }
    // } else {
    //   if(type == 'filingTable'){
    //     downloadFile(row.filingTable);
    //   }else if(type == 'brochureTable'){
    //     downloadFile(row.brochureTable);
    //   }
    // }
  };

  const handleEdit = (row) => {
    // 手动格式化时间
    const formatTime = (timeStr) => {
      if (!timeStr) return '';
      const date = new Date(timeStr);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    };

    editForm.value = {
      ...row,
      startTime: formatTime(row.startTime),
      endTime: formatTime(row.endTime),
      lowest_grade: Number(row.lowest_grade),
      top_grade: Number(row.top_grade),
      provincial: [...(row.provincial || [])],
    };

    // 打印时间值进行调试
    console.log('Original startTime:', row.startTime);
    console.log('Edited startTime:', editForm.value.startTime);

    editDialogVisible.value = true;
  };

  const submitEdit = async () => {
    if (!editFormRef.value) return;
    await editFormRef.value.validate(async (valid, fields) => {
      if (valid) {
        try {
          const formData = { ...editForm.value };

          if (Array.isArray(formData.provincial)) {
            formData.provincial = formData.provincial.join('');
          }
          const { code, msg } = await Http.post({
            url: '/yp_admin/editExamApplication',
            data: formData,
          });
          if (code === 200) {
            ElMessage.success('编辑成功');
            editDialogVisible.value = false;
            getExamApplications();
           
          } else {
            ElMessage.error(msg || '编辑失败');
          }
        } catch (error) {
          console.error('编辑失败:', error);
          ElMessage.error('编辑失败');
        }
      } else {
        console.log('表单验证失败:', fields);
      }
    });
  };

  const handleDelete = (row) => {
    ElMessageBox.confirm('确认删除该申报记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      try {
        const { code, msg } = await Http.post({
          url: '/yp_admin/deleteExamApplication',
          data: { id: row.id },
        });
        if (code === 200) {
          ElMessage.success('删除成功');
          getExamApplications();
        } else {
          ElMessage.error(msg || '删除失败');
        }
      } catch (error) {
        console.error('删除失败:', error);
        ElMessage.error('删除失败');
      }
    });
  };

  // 添加图片预览处理方法
  const handlePreviewImage = (imgUrl) => {
    if (imgUrl) {
      const url = imgUrls(imgUrl);
      window.open(url, '_blank');
    }
  };

  // 添加网盘对话框
  const webdiskDialogVisible = ref(false);
  const webdiskForm = reactive({
    id: '',
    webdisk: '',
    status_id: '',
  });

  const submitWebdisk = async () => {
    try {
      const { code, msg } = await Http.post({
        url: '/yp_admin/editWebdisk',
        data: webdiskForm,
      });
      if (code === 200) {
        ElMessage.success('编辑网盘地址成功');
        webdiskDialogVisible.value = false;
        getExamApplications();
      } else {
        ElMessage.error(msg || '编辑网盘地址失败');
      }
    } catch (error) {
      console.error('编辑网盘地址失败:', error);
      ElMessage.error('编辑网盘地址失败');
    }
  };

  // 审核对话框
  const auditDialogVisible = ref(false);
  const auditForm = reactive({
    id: '',
    status_id: '',
  });

  const submitAudit = async () => {
    try {
      const { code, msg } = await Http.post({
        url: '/yp_admin/auditExamApplication',
        data: auditForm,
      });
      if (code === 200) {
        ElMessage.success('审核成功');
        auditDialogVisible.value = false;
        getExamApplications();
      } else {
        ElMessage.error(msg || '审核失败');
      }
    } catch (error) {
      console.error('审核失败:', error);
      ElMessage.error('审核失败');
    }
  };

  // 添加判断是否可以访问报名相关功能的方法
  const canAccessRegistration = (status) => {
    return status >= 3;
  };

  // 修改导出处理方法
  const handleExport = async () => {
    try {
      const { code, data, msg } = await Http.post({
        url: '/yp_admin/downloadExamApplications',
        data: searchForm,
      });

      if (code !== 200) {
        return ElMessage.error(msg || '导出失败');
      }

      // 直接使用 window.location.href 触发下载
      window.location.href = imgUrls(data);
      // const fileUrl = imgUrls(data);
      // window.open(fileUrl, '_blank');
    } catch (error) {
      console.error('导出失败:', error);
      ElMessage.error('导出失败');
    }
  };
</script>

<style scoped lang="scss">
  .el-form--inline .el-form-item {
    margin-right: 10px !important;
    :deep(.el-input__wrapper) {
      width: 180px !important;
    }
  }
  .el-select,
  .el-input {
    width: 180px;
  }
  :deep(.el-input__wrapper) {
    height: 40px;
    line-height: 40px;
  }
  :deep(.el-form-item__label) {
    height: 40px;
    line-height: 40px;
    padding-right: 12px;
    white-space: nowrap;
  }
  .Button {
    height: 40px;
  }
  /* 隐藏number类型输入框的上下箭头 */
  :deep(input[type='number']) {
    -moz-appearance: textfield;
  }

  :deep(input[type='number']::-webkit-outer-spin-button),
  :deep(input[type='number']::-webkit-inner-spin-button) {
    -webkit-appearance: none;
    margin: 0;
  }

  .application-container {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    padding: 20px;
    overflow: hidden;

    .page-content {
      width: 100%;
      height: 100%; // 更改为100%高度
      display: flex;
      flex-direction: column;

      .form-container {
        width: 100%;
        margin-bottom: 20px;
        display: flex;
        align-items: center;
      }
      .el-table {
        flex: 1;
        width: 100%;
        overflow: scroll;
      }

      :deep(.el-table__body-wrapper) {
        overflow-y: auto;
        height: calc(100% - 40px);
      }

      /* 添加固定列样式调整 */
      :deep(.el-table__fixed-right) {
        height: 100%;

        .el-table__fixed-header-wrapper {
          background-color: var(--el-bg-color);
        }

        .el-table__fixed-body-wrapper {
          height: calc(100% - 40px);
          overflow-y: auto;
        }
      }

      .pagination-container {
        width: 100%;
        margin-top: 10px;
        padding: 10px 0;
        display: flex;
        justify-content: flex-end;
        background-color: #fff;
      }
    }
  }

  .application-form {
    max-height: 600px;
    overflow-y: auto;
    padding-right: 20px;

    .el-row {
      margin-bottom: 15px;
    }

    :deep(.el-form-item__content) {
      .el-input,
      .el-select,
      .el-cascader,
      .el-date-editor {
        width: 70%;
      }

      .el-select,
      .el-cascader {
        .el-input {
          width: 100%;
        }
      }

      .el-cascader {
        width: 70%;
        .el-input {
          width: 100%;
        }
        .el-cascader__dropdown {
          width: auto !important;
        }
      }

      .el-input__wrapper,
      .el-select__wrapper {
        height: 40px;
        line-height: 40px;
      }

      .el-input__inner {
        height: 40px;
        line-height: 40px;
        font-size: 14px;
      }
    }

    :deep(.el-form-item) {
      margin-bottom: 15px;
      .el-form-item__error {
        padding-top: 2px;
        position: absolute;
        top: 100%;
        left: 0;
      }
    }

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background-color: #dcdfe6;
      border-radius: 3px;
    }

    &::-webkit-scrollbar-track {
      background-color: #f5f7fa;
    }
  }

  .date-picker-wrapper {
    width: 70%;
  }

  :deep(.el-date-editor) {
    --el-date-editor-width: 100%;
  }

  :deep(.el-dialog__body) {
    padding: 20px;
    padding-right: 0;
  }

  .dialog-footer {
    padding: 20px 0;
    text-align: right;
  }

  .avatar-uploader {
    :deep(.el-upload) {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    :deep(.el-upload:hover) {
      border-color: var(--el-color-primary);
    }
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    line-height: 178px;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
    object-fit: cover;
  }

  .button-group {
    display: flex;
    flex-direction: column;
    gap: 4px; // 行间距
  }

  .button-row {
    display: flex;
    gap: 4px; // 按钮间距
    flex-wrap: nowrap; // 防止按钮换行

    :deep(.el-button) {
      flex: 1; // 让操作列的按钮等宽
      padding: 4px 8px;
      margin: 0;
      white-space: nowrap;
    }
  }

  // 为管理列的按钮添加特殊样式
  .el-table-column--management {
    .button-row {
      :deep(.el-button) {
        flex: none; // 管理列的按钮不等宽
      }
    }
  }

  .view-content {
    padding: 20px;

    :deep(.el-descriptions__body) {
      background-color: #fff;
    }

    :deep(.el-descriptions__cell) {
      user-select: none; // 禁止文本选择
    }

    :deep(.el-descriptions__table) {
      // 禁用表格的默认点击效果
      &:active,
      &:focus {
        outline: none;
      }
    }

    .preview-img {
      width: 120px;
      height: 120px;
      object-fit: cover;
      cursor: pointer;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      transition: all 0.3s;

      &:hover {
        transform: scale(1.05);
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      }
    }
  }

  .form-container {
    margin-bottom: 20px;

    .left-section {
      // flex: 1;

      .search-form {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        gap: 10px;

        :deep(.el-form-item) {
          margin-bottom: 0;
          margin-right: 0;
        }
      }
    }

    .right-section {
      margin-left: 16px;
      display: flex;
      gap: 8px; // 添加按钮之间的间距
    }
  }
  .dialogBox {
    width: 100%;
    display: flex;
    align-items: center;
    margin-bottom: 20px;
  }
  .labelName {
    width: 70px;
  }
</style>
